package com.free.others;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

/**
 * <p>
 * Title: Eclipse Plugin Development
 * </p>
 * <p>
 * Description: Free download
 * </p>
 * <p>
 * mail: ganshm@gmail.com
 * </p>
 */

public class SimpleDNDExample
{ // drag and drop
    
    public static void main(String[] args)
    {
        Shell shell = new Shell();
        shell.setLayout(new FillLayout());
        
        // 添加树组件
        final Tree tree = new Tree(shell, SWT.NONE);
        // 添加树子结点
        TreeItem item1 = new TreeItem(tree, SWT.NONE);
        item1.setText("Item 1");
        TreeItem item2 = new TreeItem(tree, SWT.NONE);
        item2.setText("Item 2");
        TreeItem item3 = new TreeItem(tree, SWT.NONE);
        item3.setText("Item 3");
        TreeItem item4 = new TreeItem(tree, SWT.NONE);
        item4.setText("Item 4");
        
        // 新建拖放的数据源
        DragSource ds = new DragSource(tree, DND.DROP_MOVE);
        // 设置可数据源可拖入的类型
        ds.setTransfer(new Transfer[] {TextTransfer.getInstance()});
        // 添加拖动事件监听器
        ds.addDragListener(new DragSourceAdapter()
        {
            public void dragSetData(DragSourceEvent event)
            {
                // 设置当前选定的第一个结点为拖动数据
                event.data = tree.getSelection()[0].getText();
            }
        });
        
        final Button button = new Button(shell, SWT.FLAT);
        button.setText("Button");
        button.setAlignment(SWT.CENTER);
        
        // 新建拖放的目标
        DropTarget dt = new DropTarget(button, DND.DROP_MOVE);
        // 设置可接收数据的类型
        dt.setTransfer(new Transfer[] {TextTransfer.getInstance()});
        // 设置拖放事件监听器，监听鼠标放下事件
        dt.addDropListener(new DropTargetAdapter()
        {
            public void drop(DropTargetEvent event)
            {
                // 设置按钮显示文本为数据源的文本
                button.setText((String)event.data);
            }
        });
        
        shell.pack();
        shell.open();
        Display display = Display.getDefault();
        while (!shell.isDisposed())
            if (!display.readAndDispatch())
                display.sleep();
        display.dispose();
    }
    
}
